import React, { useState, useEffect, useRef } from 'react';
import { getVNCInfo } from '../api/client';

interface VNCInfo {
  host: string;
  port: number;
  websocket_port: number;
  password?: string;
  console_websocket_url?: string;
}

interface VNCViewerProps {
  domainName: string;
  isOpen: boolean;
  onClose: () => void;
}

const VNCViewer: React.FC<VNCViewerProps> = ({ domainName, isOpen, onClose }) => {
  const [vncInfo, setVNCInfo] = useState<VNCInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [connected, setConnected] = useState(false);
  const iframeRef = useRef<HTMLIFrameElement>(null);

  useEffect(() => {
    if (isOpen && domainName) {
      loadVNCInfo();
    }
  }, [isOpen, domainName]);

  const loadVNCInfo = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await getVNCInfo(domainName);
      setVNCInfo(response.data);
      setConnected(true);
    } catch (err: any) {
      console.error('Failed to load VNC info:', err);
      setError(err.response?.data?.detail || 'Failed to load VNC information');
      setConnected(false);
    } finally {
      setLoading(false);
    }
  };


  const getNoVNCURL = (info: VNCInfo) => {
    const host = info.host || window.location.hostname;
    const port = info.websocket_port || (info.port >= 5900 ? info.port + 1000 : 6900);
    const path = `/api/v1/domains/${domainName}/vnc/websocket`;
    
    // 使用本地的noVNC客户端，通过URL参数传递连接信息
    return `/vnc-client.html?host=${host}&port=${port}&path=${encodeURIComponent(path)}&autoconnect=true`;
  };

  if (!isOpen) {
    return null;
  }

  return (
    <div className="vnc-viewer-modal">
      <div className="vnc-modal-overlay" onClick={onClose}>
        <div className="vnc-modal-content" onClick={(e) => e.stopPropagation()}>
          <div className="vnc-modal-header">
            <h2>VNC Viewer - {domainName}</h2>
            <button className="vnc-close-btn" onClick={onClose} title="Close">
              ✕
            </button>
          </div>

          <div className="vnc-modal-body">
            {loading && (
              <div className="vnc-loading">
                <div className="loading-spinner"></div>
                <p>Loading VNC information...</p>
              </div>
            )}

            {error && (
              <div className="vnc-error">
                <div className="error-icon">⚠️</div>
                <h3>VNC Connection Error</h3>
                <p>{error}</p>
                <div className="error-actions">
                  <button onClick={loadVNCInfo} className="primary">
                    Retry
                  </button>
                  <button onClick={onClose} className="secondary">
                    Close
                  </button>
                </div>
              </div>
            )}

            {vncInfo && !loading && !error && (
              <div className="vnc-connection-info">
                <div className="vnc-info-panel">
                  <h4>Connection Information</h4>
                  <div className="info-grid">
                    <div className="info-item">
                      <span className="info-label">Host:</span>
                      <span className="info-value">{vncInfo.host}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">VNC Port:</span>
                      <span className="info-value">{vncInfo.port}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">WebSocket Port:</span>
                      <span className="info-value">{vncInfo.websocket_port || (vncInfo.port - 5900 + 6900)}</span>
                    </div>
                    {vncInfo.password && (
                      <div className="info-item">
                        <span className="info-label">Password:</span>
                        <span className="info-value">••••••••</span>
                      </div>
                    )}
                    {vncInfo.console_websocket_url && (
                      <div className="info-item">
                        <span className="info-label">Console URL:</span>
                        <span className="info-value">{vncInfo.console_websocket_url}</span>
                      </div>
                    )}
                  </div>
                </div>

                <div className="vnc-viewer-container">
                  <h4>VNC Viewer</h4>
                  <div className="vnc-iframe-container">
                    <iframe
                      ref={iframeRef}
                      src={getNoVNCURL(vncInfo)}
                      title={`VNC Viewer for ${domainName}`}
                      className="vnc-iframe"
                      allowFullScreen
                      sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
                    />
                  </div>

                  <div className="vnc-controls">
                    <button
                      onClick={() => iframeRef.current?.contentWindow?.location.reload()}
                      className="secondary"
                      title="Reconnect VNC"
                    >
                      🔄 Reconnect
                    </button>
                    <button
                      onClick={() => iframeRef.current?.requestFullscreen?.()}
                      className="secondary"
                      title="Full Screen"
                    >
                      ⛶ Full Screen
                    </button>
                    <button onClick={loadVNCInfo} className="secondary">
                      🔄 Refresh Info
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="vnc-modal-footer">
            <div className="connection-status">
              <span className={`status-indicator ${connected ? 'connected' : 'disconnected'}`}>
                {connected ? '🟢 Connected' : '🔴 Disconnected'}
              </span>
            </div>
            <button onClick={onClose} className="secondary">
              Close
            </button>
          </div>
        </div>
      </div>

      <style>{`
        .vnc-viewer-modal {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 1000;
        }

        .vnc-modal-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
        }

        .vnc-modal-content {
          background: white;
          border-radius: 8px;
          box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
          max-width: 95vw;
          max-height: 95vh;
          width: 1200px;
          height: 800px;
          display: flex;
          flex-direction: column;
        }

        .vnc-modal-header {
          padding: 20px;
          border-bottom: 1px solid #e0e0e0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .vnc-modal-header h2 {
          margin: 0;
          font-size: 1.5em;
          color: #333;
        }

        .vnc-close-btn {
          background: none;
          border: none;
          font-size: 1.5em;
          cursor: pointer;
          padding: 5px;
          border-radius: 4px;
        }

        .vnc-close-btn:hover {
          background: #f0f0f0;
        }

        .vnc-modal-body {
          flex: 1;
          padding: 20px;
          overflow: auto;
        }

        .vnc-loading, .vnc-error {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          text-align: center;
        }

        .loading-spinner {
          width: 40px;
          height: 40px;
          border: 4px solid #f3f3f3;
          border-top: 4px solid #007bff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-bottom: 20px;
        }

        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }

        .vnc-error .error-icon {
          font-size: 3em;
          margin-bottom: 20px;
        }

        .vnc-error h3 {
          margin: 0 0 10px 0;
          color: #dc3545;
        }

        .vnc-error p {
          margin: 0 0 20px 0;
          color: #666;
        }

        .error-actions {
          display: flex;
          gap: 10px;
        }

        .vnc-connection-info {
          display: flex;
          flex-direction: column;
          height: 100%;
          gap: 20px;
        }

        .vnc-info-panel {
          background: #f8f9fa;
          padding: 15px;
          border-radius: 6px;
          border: 1px solid #dee2e6;
        }

        .vnc-info-panel h4 {
          margin: 0 0 15px 0;
          color: #495057;
        }

        .info-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 10px;
        }

        .info-item {
          display: flex;
          justify-content: space-between;
          padding: 5px 0;
        }

        .info-label {
          font-weight: bold;
          color: #495057;
        }

        .info-value {
          color: #6c757d;
          font-family: monospace;
        }

        .vnc-viewer-container {
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 15px;
        }

        .vnc-iframe-container {
          flex: 1;
          border: 1px solid #dee2e6;
          border-radius: 6px;
          overflow: hidden;
        }

        .vnc-iframe {
          width: 100%;
          height: 100%;
          border: none;
        }

        .vnc-controls {
          display: flex;
          gap: 10px;
          justify-content: flex-end;
        }

        .vnc-modal-footer {
          padding: 15px 20px;
          border-top: 1px solid #e0e0e0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .status-indicator {
          font-weight: bold;
        }

        .status-indicator.connected {
          color: #28a745;
        }

        .status-indicator.disconnected {
          color: #dc3545;
        }

        button {
          padding: 8px 16px;
          border: 1px solid #ddd;
          border-radius: 4px;
          background: white;
          cursor: pointer;
          font-size: 0.9em;
        }

        button:hover {
          background: #f8f9fa;
        }

        button.primary {
          background: #007bff;
          color: white;
          border-color: #007bff;
        }

        button.primary:hover {
          background: #0056b3;
        }

        button.secondary {
          background: #6c757d;
          color: white;
          border-color: #6c757d;
        }

        button.secondary:hover {
          background: #545b62;
        }

        button.danger {
          background: #dc3545;
          color: white;
          border-color: #dc3545;
        }

        button.danger:hover {
          background: #c82333;
        }
      `}</style>
    </div>
  );
};

export default VNCViewer;